package ims.com.shlcm.jfreechart;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.servlet.ChartDeleter;
import org.jfree.chart.servlet.ServletUtilities;

public class CmDisplayChart extends HttpServlet {
	private static Log log = LogFactory.getLog(CmDisplayChart.class);
	//ims.com.shlcm.jfreechart.CmDisplayChart
	//http://pdm10.shlcm.com/Windchill/CmDisplayChart?filename=jfreechart-1188797911590765385.png
	private static final long serialVersionUID = 1L;
	public CmDisplayChart(){
		
	}

	@Override
	public void init() throws ServletException {
	}


	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("CmDisplayChart...");
		HttpSession session = request.getSession();
		String filename = request.getParameter("filename");
		if (filename == null){
			throw new ServletException("Parameter 'filename' must be supplied");
		}
		filename = ServletUtilities.searchReplace(filename, "..", "");
		File file = new File(System.getProperty("java.io.tmpdir"), filename);
		if (!file.exists()){
			throw new ServletException("File '" + file.getAbsolutePath()+ "' does not exist");
		}
		if(log.isDebugEnabled()){
			log.debug("filename :"+filename);
			log.debug("file.getCanonicalPath :"+file.getCanonicalPath());
		}
		boolean isChartInUserList = false;
		ChartDeleter chartDeleter = (ChartDeleter) session.getAttribute("JFreeChart_Deleter");
		if (chartDeleter != null){
			isChartInUserList = chartDeleter.isChartAvailable(filename);
		}
		boolean isChartPublic = false;
		if (filename.length() >= 6 && filename.substring(0, 6).equals("public")){
			isChartPublic = true;
		}
		boolean isOneTimeChart = false;
		if (filename.startsWith(ServletUtilities.getTempOneTimeFilePrefix())){
			isOneTimeChart = true;
		}
		if(log.isDebugEnabled()){
			log.debug("isChartInUserList :"+isChartInUserList);
			log.debug("isChartPublic :"+isChartPublic);
			log.debug("isOneTimeChart :"+isOneTimeChart);
		}
		if (isChartInUserList || isChartPublic || isOneTimeChart) {
			ServletUtilities.sendTempFile(file, response);
			if (isOneTimeChart){
				file.delete();
			}
		} else {
			throw new ServletException("Chart image not found");
		}
	}

}
